﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using System.IO;
using PServiceBus.Core.Runtime.Configuration;

namespace PServiceBus.Core.Logger {
    public class TextLogger : ILogger {
        private string _filename = ConfigurationProvider.LoggerConfig.LogPath;
        private string _exceptionFilename = ConfigurationProvider.LoggerConfig.ErrorLogPath;
        private object _lockObject = new object();
        #region ILogger Members

        public void Log(string text, params object[] args) {
            Write(_filename, String.Format(text, args));
        }

        private void Write(string filename, string text) {
            lock (_lockObject) {
                if (String.IsNullOrWhiteSpace(filename)) return;
                filename = filename.Replace("\\", "/");
                var fileInfo = new FileInfo(filename);
                filename = String.Format("{0}/{1}_{2}{3}", 
                    fileInfo.DirectoryName, fileInfo.Name, 
                    DateTime.Now.ToString("MM_dd_yyyy"), fileInfo.Extension);
                using (var s = new StreamWriter(File.Open(filename, FileMode.Append, FileAccess.Write, FileShare.Write)))
                    s.WriteLine(text);
            }
        }

        public void Log(Exception ex) {
            Write(_exceptionFilename, String.Format("Error occurred at {0}\r\n{1}\r\n-----------------------\r\n", DateTime.Now, ex.ToString()));
        }

        #endregion
    }
}
